﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using crmservice;
using System.Text;

public partial class OASYS : System.Web.UI.Page
{
    private CrmService crm;

    protected void Page_Load(object sender, EventArgs e)
    {
        crm = CRMServiceFactory.CreateCRMService(ConfigurationManager.AppSettings.Get("CRMOrganizationName"));
        if (true ) //!Page.IsPostBack)
        {
            Utilities.LoadStateDropDownList(crm, ref ddlState);
            Utilities.LoadStateDropDownList(crm, ref ddlBizState);
            Utilities.LoadEthnicityDropDownList(crm, ref ddlEthnicGroup);
            string Script = Utilities.BuildBoardJavascript(crm);
            Page.RegisterStartupScript("OASYSScript", Script);
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (Page.IsValid == false) return;
        try
        {
            oasys_transistionapplication app = new oasys_transistionapplication();

            app.oasys_titleprefix = txtTitle.Text;
            app.oasys_firstname = txtFirstName.Text;
            app.oasys_middlename = txtMiddleName.Text;
            app.oasys_lastname = txtLastName.Text;
            app.oasys_suffix = txtSuffix.Text;
            app.oasys_name = Utilities.BuildFullName(app.oasys_firstname, app.oasys_middlename, app.oasys_lastname);

            app.oasys_othernamesaliasesexplanation = txtOtherNames.Text;
            app.oasys_email = txtEmail.Text;
            //app.oasys_emailaddress = txtEmail.Text;
            app.oasys_homephone = txtHomePhone.Text;
            //app.oasys_homephoneextension = txtHomePhoneExtension.Text;
            app.oasys_cellularphone = txtCellPhone.Text;
            app.gov_workphone = txtWorkPhone.Text;
            app.oasys_homestreetaddress1 = txtAddress1.Text;
            app.oasys_homestreetaddress2 = txtAddress2.Text;
            app.oasys_city = txtCity.Text;
            app.oasys_stateprovince = ddlState.SelectedItem.Text;
            app.oasys_zipcode = txtZip.Text;
            app.gov_workaddressline1 = txtBizAddress1.Text;
            app.gov_workaddressline2 = txtBizAddress2.Text;
            app.gov_workcity = txtBizCity.Text;
            app.gov_workstate = ddlBizState.SelectedItem.Text;
            app.gov_workzipcode = txtBizZipCode.Text;

            //app.oasys_zip4 = txtZip4.Text;
            app.oasys_education = txtEducation.Text;
            app.oasys_employmentexperience = txtEmployment.Text;
            app.oasys_professionallicenses = txtLicenses.Text;
            app.oasys_previousgovernmentappointments = txtAppointments.Text;
            app.oasys_honorsawards = txtHonors.Text;
            app.oasys_references = txtReferences.Text;

            //Military
            app.oasys_militaryserviceexplanation = txtMilitaryService.Text;
            if (radDishonorableDischargeYes.Checked)
                app.oasys_militaryhonorabledischarge = "Less than honorable";
            else if (radDishonorableDischargeNo.Checked)
                app.oasys_militaryhonorabledischarge = "Honorable";
            else
                app.oasys_militaryhonorabledischarge = "Not answered";
            app.oasys_militarydischargeexplanation = txtDischargeExplanation.Text;
            app.oasys_militaryreservesnationalguard = Utilities.RadioButtonToPickList(radReservesYes, radReservesNo);
            app.oasys_militaryobligationenddate = new CrmDateTime();
            app.oasys_militaryobligationenddate.Value = txtReservesEndDate.Text;

            //Vetting
            app.oasys_busrelationshiplobbying = Utilities.RadioButtonToPickList(radBusinessLobbyingYes, radBusinessLobbyingNo);
            app.oasys_businessrelationshipslobbyingexplain = txtBusinessLobbying.Text;
            app.oasys_citation = Utilities.RadioButtonToPickList(radCitationsYes, radCitationsNo);
            app.oasys_citationsexplanation = txtCitations.Text;
            app.oasys_convictions = Utilities.RadioButtonToPickList(radConvictionsYes, radConvictionsNo);
            app.oasys_convictionexplanation = txtConvictions.Text;
            app.oasys_currentcharge = Utilities.RadioButtonToPickList(radChargesYes, radChargesNo);
            app.oasys_currentchargesexplanation = txtCharges.Text;
            app.oasys_oppostionassociation = Utilities.RadioButtonToPickList(radOppositionYes, radOppositionNo);
            app.oasys_oppositionsassociationsexplanation = txtOpposition.Text;
            app.oasys_delinquency = Utilities.RadioButtonToPickList(radDelinquenciesYes, radDelinquenciesNo);
            app.oasys_delinquenciesexplanation = txtDelinquencies.Text;
            app.oasys_issues_ = Utilities.RadioButtonToPickList(radIssuesYes, radIssuesNo);
            app.oasys_issuesexplanation = txtIssues.Text;
            app.oasys_controversialview = Utilities.RadioButtonToPickList(radViewsYes, radViewsNo);
            app.oasys_controversialviewsexplanation = txtViews.Text;
            app.oasys_proceeding = Utilities.RadioButtonToPickList(radProceedingsYes, radProceedingsNo);
            app.oasys_proceedingsexplaination = txtProceedings.Text;
            app.oasys_familyproceeding = Utilities.RadioButtonToPickList(radCivilLitigationYes, radCivilLitigationNo);
            app.oasys_familyproceedingexplanation = txtCivilLitigation.Text;
            app.oasys_legalproceeding = Utilities.RadioButtonToPickList(radLegalProceedingsYes, radLegalProceedingsNo);
            app.oasys_legalproceedingexplanation = txtLegalProceedings.Text;
            app.oasys_firmcharge = Utilities.RadioButtonToPickList(radChargesAssociatesYes, radChargesAssociatesNo);
            app.oasys_firmchargesexplanation = txtCharges.Text;
            app.oasys_discrimination_ = Utilities.RadioButtonToPickList(radDiscriminationYes, radDiscriminationNo);
            app.oasys_discriminationexplanation = txtDiscrimination.Text;
            app.oasys_credit_history = Utilities.RadioButtonToPickList(radCreditHistoryYes, radCreditHistoryNo);
            app.oasys_credithistoryexplanation = txtCreditHistory.Text;
            app.oasys_controversy_ = Utilities.RadioButtonToPickList(radControversyYes, radControversyNo);
            app.oasys_controversyexplanation = txtControversy.Text;
            app.oasys_affiliatonsexplanation = txtAffiliations.Text;
            app.oasys_citizen_seat = Utilities.RadioButtonToPickList(radCitzenMemberYes, radCitzenMemberNo);
            app.oasys_citizenseatexplanation = txtCitzenMember.Text;

            //Demographics
            app.oasys_dateofbirth = new CrmDateTime();
            app.oasys_dateofbirth.Value = txtDOB.Text;
            app.oasys_citizenship_status = Utilities.RadioButtonToPickList(radUSCitizenYes, radUSCitizenNo);
            app.oasys_gender = Utilities.RadioButtonToPickList(radGenderMale, radGenderFemale);
            app.oasys_disability = txtDisability.Text;
            app.oasys_ethnicgroup = ddlEthnicGroup.SelectedItem.Text;
            app.oasys_country = txtBirthCountry.Text;

            //Boards
            string[] BoardIDs = null;
            if (Request["lstSelectedBoards"] != null)
            {
                StringBuilder sbBoards = new StringBuilder();
                BoardIDs = Request["lstSelectedBoards"].Split(new char[] { ',' });
                foreach (string BoardID in BoardIDs)
                {
                    ColumnSet cols = new ColumnSet();
                    cols.Attributes = new string[] { "oasys_displayname" };
                    oasys_boardsandcommissionsmasterlist Board = (oasys_boardsandcommissionsmasterlist)crm.Retrieve("oasys_boardsandcommissionsmasterlist", new Guid(BoardID), cols);
                    sbBoards.Append(Board.oasys_displayname + " | ");
                }
                sbBoards.Length -= 3;
                app.oasys_requestedboardappointments = sbBoards.ToString();
            }

            app.oasys_applicationstatus = new Picklist();
            app.oasys_applicationstatus.Value = 1;
            app.oasys_applicationsubmitteddate = new CrmDateTime();
            app.oasys_applicationsubmitteddate.Value = DateTime.Now.ToString();
            app.oasys_applicationcreatedondate = app.oasys_applicationsubmitteddate;
            app.oasys_modifiedondate = app.oasys_applicationsubmitteddate;

            Guid AppID = crm.Create(app);
            if (AppID != null)
            {
                if (ResumeUploader.HasFile)
                {
                    UploadResume(AppID);
                }

                AssociateEntitiesRequest AppBoardRequest = new AssociateEntitiesRequest();
                AppBoardRequest.RelationshipName = "oasys_oasys_transistionapplication_oasys_boards";
                AppBoardRequest.Moniker1 = new Moniker();
                AppBoardRequest.Moniker1.Id = AppID;
                AppBoardRequest.Moniker1.Name = "oasys_transistionapplication";
                AppBoardRequest.Moniker2 = new Moniker();
                AppBoardRequest.Moniker2.Name = "oasys_boardsandcommissionsmasterlist";

                if (BoardIDs != null)
                {
                    foreach (string BoardID in BoardIDs)
                    {
                        AppBoardRequest.Moniker2.Id = new Guid(BoardID);
                        crm.Execute(AppBoardRequest);
                    }
                }
            }

            Server.Transfer("~/OASYSResult.aspx");
        }
        catch (Exception ex)
        {
            lblError.Text = string.Format("An error occurred while submitting the application: {0}", ex.Message + " " + ex.StackTrace);
        }
    }

    protected void vldVetting_ServerValidate(object source, ServerValidateEventArgs args)
    {
        string em = null;

        if (Utilities.RadioButtonToPickList(radBusinessLobbyingYes, radBusinessLobbyingNo) == null) em += "<li>Registered lobbyist answer is required</li>";
        if (Utilities.RadioButtonToPickList(radCitationsYes, radCitationsNo) == null) em += "<li>Citations answer is required</li>";
        if (Utilities.RadioButtonToPickList(radConvictionsYes, radConvictionsNo) == null) em += "<li>Convictions answer is required</li>";
        if (Utilities.RadioButtonToPickList(radChargesYes, radChargesNo) == null) em += "<li>Charges answer is required</li>";
        if (Utilities.RadioButtonToPickList(radOppositionYes, radOppositionNo) == null) em += "<li>Opposition answer is required</li>";
        if (Utilities.RadioButtonToPickList(radDelinquenciesYes, radDelinquenciesNo) == null) em += "<li>Delinquencies answer is required</li>";
        if (Utilities.RadioButtonToPickList(radIssuesYes, radIssuesNo) == null) em += "<li>Issues answer is required</li>";
        if (Utilities.RadioButtonToPickList(radViewsYes, radViewsNo) == null) em += "<li>Views answer is required</li>";
        if (Utilities.RadioButtonToPickList(radProceedingsYes, radProceedingsNo) == null) em += "<li>Proceedings answer is required</li>";
        if (Utilities.RadioButtonToPickList(radCivilLitigationYes, radCivilLitigationNo) == null) em += "<li>Civil Litigation answer is required</li>";
        if (Utilities.RadioButtonToPickList(radLegalProceedingsYes, radLegalProceedingsNo) == null) em += "<li>Leagal Proceedings answer is required</li>";
        if (Utilities.RadioButtonToPickList(radChargesAssociatesYes, radChargesAssociatesNo) == null) em += "<li>Charges / Associates answer is required</li>";
        if (Utilities.RadioButtonToPickList(radDiscriminationYes, radDiscriminationNo) == null) em += "<li>Discrimination answer is required</li>";
        if (Utilities.RadioButtonToPickList(radCreditHistoryYes, radCreditHistoryNo) == null) em += "<li>Credit History answer is required</li>";
        if (Utilities.RadioButtonToPickList(radControversyYes, radControversyNo) == null) em += "<li>Controversy answer is required</li>";
        

        if (em != null)
        {
            vldVetting.ErrorMessage = "Vetting section is missing the following answers:" + em;
            valSummary.HeaderText = "Please correct the following errors and press Submit again. Note, you will have to reselect your Board(s) and Resume file.";
            args.IsValid = false;
        }
    }

    void UploadResume(Guid AppID)
    {
        string FilePath = Server.MapPath(string.Format("App_Data/{0}.{1}", AppID.ToString(), Path.GetExtension(ResumeUploader.FileName)));
        ResumeUploader.SaveAs(FilePath);
        if (File.Exists(FilePath))
        {
            annotation note = new annotation();
            note.notetext = "Resume uploaded with OASYS";
            note.subject = "Resume";
            note.objectid = new Lookup();
            note.objectid.type = "oasys_transistionapplication";
            note.objectid.Value = AppID; 
            note.objecttypecode = new EntityNameReference();
            note.objecttypecode.Value = "oasys_transistionapplication";

            Guid NoteID = crm.Create(note);

            FileStream stream = File.OpenRead(FilePath);
            byte[] byteData = new byte[stream.Length];
            stream.Read(byteData, 0, byteData.Length);
            stream.Close();

            string encodedData = System.Convert.ToBase64String(byteData);

            annotation updateNote = new annotation();
            updateNote.annotationid = new Key();
            updateNote.annotationid.Value = NoteID; 
            updateNote.documentbody = encodedData;
            updateNote.filename = Path.GetFileName(FilePath);
            if (updateNote.filename.EndsWith(".pdf", StringComparison.CurrentCultureIgnoreCase))
                updateNote.mimetype = @"application/pdf";
            else
                updateNote.mimetype = @"application/msword";

            crm.Update(updateNote);
            crm.Dispose();

            File.Delete(FilePath);
        }
    }
    protected void vldBoards_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = (Request["lstSelectedBoards"] != null);
    }

    protected void vldResume_ServerValidate(object source, ServerValidateEventArgs args)
    {
        string filename = ResumeUploader.FileName;
        args.IsValid = (filename.EndsWith(".docx", StringComparison.CurrentCultureIgnoreCase) ||
                        filename.EndsWith(".doc", StringComparison.CurrentCultureIgnoreCase) ||
                        filename.EndsWith(".pdf", StringComparison.CurrentCultureIgnoreCase));
    }
}
